package com.java.json;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.java.pojo.Person;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jingjintao
 * @date 2021/6/22 - 22:13
 **/
public class JsonTest {

    //JavaBean和json字符串互转
    @Test
    public void test1(){
        Person person = new Person(1,"井锦涛");
        Gson gson = new Gson();
        String personJsonString = gson.toJson(person);
        System.out.println(personJsonString);

        Person person1 = gson.fromJson(personJsonString, Person.class);
        System.out.println(person1);
    }
    //List和json字符串互转
    @Test
    public void test2(){
        List<Person> list = new ArrayList<>();
        list.add(new Person(1,"井锦涛"));
        list.add(new Person(2,"汤姆猫"));

        Gson gson = new Gson();
        String listJsonString = gson.toJson(list);
        System.out.println(listJsonString);

        List<Person>  list2= gson.fromJson(listJsonString,new TypeToken<ArrayList<Person>>(){}.getType());
        list2.forEach(System.out::println);
    }
    //Map和json字符串互转
    @Test
    public void test3(){
        Map<Integer,Person> map = new HashMap<>();
        map.put(1,new Person(1,"井锦涛"));
        map.put(2,new Person(2,"汤姆猫"));

        Gson gson = new Gson();
        String mapJsonString = gson.toJson(map);
        System.out.println(mapJsonString);

        Map<Integer,Person> map2 = gson.fromJson(mapJsonString,new TypeToken<HashMap<Integer,Person>>(){}.getType());
        Person person = map2.get(2);
        System.out.println(person);
    }
}
